<script setup lang="ts">
import {h, onMounted, ref} from "vue";
import CustomModal from "@components/CustomModal";
import {BoxOpen} from "@vicons/fa";
import {NButton, type SelectOption, NSelect, type FormInst, useMessage} from "naive-ui";
import {getRequest, postRequest, putRequest} from "@/api";
import {UgJoditEditor} from "ug-jodit-editor";

interface AgreementList {
  label: string;
  status: number;
  status_text: string;
  title: string;
  value: string;
  version: null | number | string;
}

interface Agreement {
  types: string | null;
  title: string;
  content: string;
}

const message = useMessage()

const emits = defineEmits(['close'])

const showAgreementList = ref<boolean>(false)
const agreementList = ref<AgreementList[]>([])

const statusOptions: SelectOption[] = [
  {
    label: '草稿',
    value: 0,
  }, {
    label: '已发布',
    value: 1,
  },
  {
    label: '归档',
    value: 2,
  }
]
const columns = [
  {
    title: '协议类型',
    key: 'label',
    width: 100,
  }, {
    title: '协议名称',
    key: 'title'
  },
  {
    title: '版本',
    key: 'version',
    width: 100,
  }, {
    title: '状态',
    key: 'status',
    width: 120,
    render: (row: { id:number,status: number }) => {
      return h(NSelect,
          {
            size: "small",
            value: row.status,
            options: statusOptions,
            disabled: !row.id,
            menuProps: {
              style: '--n-option-height-small: 26px; --n-option-height: 26px;'
            },
            onUpdateValue: (value: number) => {
              //修改状态
              if(row.id){
                putRequest("/sett/up_agree_status",{id:row.id,status:value}).then((res:ResponseResult)=>{
                  if(res.code == 200){
                    message.success(res.message)
                    row.status = value;
                  }
                })
              }
            }
          },
      )
    }
  }, {
    title: '操作',
    width: 90,
    render: (row: { label: string,value:string, title: string, content: string }) => {
      const btn = [
        h(NButton, {
          type: 'info',
          text: true,
          onClick: () => {
            preview.value.title=row.title;
            preview.value.content=row.content;
            preview.value.open=true;
          }
        }, {default: () => ('预览')}),
        h(NButton, {
          type: 'primary',
          text: true,
          onClick: () => {
            editForm.value.title = row.title;
            editForm.value.content = row.content;
            editForm.value.types = row.value;
            editModalTitle.value = row.label;
            openEditModal.value = true;
          }
        }, {default: () => ('修改')})
      ]
      return h('div', {
        style: {
          display: 'flex',
          gap: '8px'
        }
      }, {default: () => (btn)})
    }
  }
]

//修改政策协议
const openEditModal = ref<boolean>(false);
const editModalTitle = ref<string>('')
const editRef = ref<FormInst | null>(null)
const submitLoading = ref<boolean>(false);
const editForm = ref<Agreement>({
  types: null,
  title: '',
  content: '',
})
const editFormRule = ref({
  title: {
    type: 'string',
    required: true,
    trigger: ['input', 'blur'],
    message: '请填写协议标题'
  },
  content: {
    type: 'string',
    required: true,
    message: '请填写协议内容'
  }
})

//预览协议
const preview=ref({
  open:false,
  content:'',
  title:'',
})

const getAgreeList = async () => {
  await getRequest("/sett/agree_list").then((res: ResponseResult) => {
    agreementList.value = res.data as AgreementList[];
  })
}

const saveAgree = () => {
  editRef.value?.validate((errors) => {
    if (!errors) {
      submitLoading.value = true;
      postRequest('/sett/save_agree', editForm.value).then((res: ResponseResult) => {
        if (res.code == 200) {
          message.success(res.message, {
            duration: 1500,
            onLeave() {
              openEditModal.value = false;
              setTimeout(()=>{
                getAgreeList();
              },300)
            }
          })
        } else {
          submitLoading.value = false;
        }
      }).catch(() => {
        submitLoading.value = false;
      })
    }
  })
}

onMounted(() => {
  getAgreeList();
  showAgreementList.value = true
})
</script>

<template>
  <div>
    <custom-modal v-model:show="showAgreementList" title="政策协议"
                  :has-action="false"
                  :widths="880" @after-leave="emits('close')">
      <template #default>
        <n-data-table :columns="columns"
                      size="small"
                      :data="agreementList">
          <template #empty>
            <n-empty description="暂无相关数据">
              <template #icon>
                <n-icon size="42">
                  <BoxOpen/>
                </n-icon>
              </template>
            </n-empty>
          </template>
        </n-data-table>
        <n-p :depth="3"><span style="color: red">*</span>&nbsp;政策协议每次修订均将自动生成新版本。</n-p>
      </template>
    </custom-modal>
    <!--  修改政策协议  -->
    <custom-modal v-model:show="openEditModal"
                  :title="editModalTitle"
                  :handel-submit-loading="submitLoading"
                  :widths="1110" @confirm="saveAgree">
      <template #default>
        <n-form ref="editRef" :model="editForm" :rules="editFormRule"
                label-placement="left" require-mark-placement="left">
          <n-form-item label="标题" path="title">
            <n-input v-model:value="editForm.title" placeholder="请填写协议标题" style="width: 300px" clearable/>
          </n-form-item>
          <n-form-item label="内容" path="content">
            <ug-jodit-editor v-model:value="editForm.content"/>
          </n-form-item>
        </n-form>
      </template>
    </custom-modal>
    <!-- 预览协议   -->
    <custom-modal v-model:show="preview.open" :title="`预览${preview.title}`" :has-action="false" :widths="880">
      <template #default>
        <div v-html="preview.content" style="height: 600px;overflow:auto;"></div>
      </template>
    </custom-modal>
  </div>
</template>

<style lang="scss">


</style>